<?php

namespace app\zmt\controller;

use app\zmt\model\GoodsModel;
use app\zmt\model\GoodsDetailsModel;
use app\zmt\validate\GoodsValidate;
use cmf\controller\AdminBaseController;
use think\facade\Db;

class GoodsController extends AdminBaseController
{
    protected $typeMap = [
        0 => '自营',
        1 => '旗舰店',
    ];

    protected $statusMap = [
        0 => '缺货',
        1 => '上架',
        2 => '下架',
    ];

    public function index()
    {
        $keyword = input('get.keyword', '');
        $where = [];
        if ($keyword) {
            $where[] = ['title', 'like', '%' . $keyword . '%'];
        }

        $goodsList = GoodsModel::where($where)
            ->order("list_order", 'desc')
            ->paginate(10);

        $page = $goodsList->render();

        $this->assign('goodsList', $goodsList);
        $this->assign('typeMap', $this->typeMap);
        $this->assign('statusMap', $this->statusMap);
        $this->assign('page', $page);
        return $this->fetch();
    }

    public function add()
    {
        return $this->fetch();
    }

    public function addPost()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $data['images'] = isset($data['photos_url']) ? implode(',', $data['photos_url']) : '';

            $validate = new GoodsValidate();
            if (!$validate->scene('addpost')->check($data)) {
                $this->error($validate->getError());
            }

            $goods = new GoodsModel($data);
            $goods->create_time = date('Y-m-d H:i:s');

            if ($goods->save()) {
                $this->success('添加成功', url('goods/index'));
            } else {
                $this->error('添加失败');
            }
        }
    }

    public function changeStatus()
    {
        $id = input('param.id', 0, 'intval');
        $goods = GoodsModel::find($id);

        if ($goods) {
            $goods->switch = ($goods->switch + 1) % 3;
            if ($goods->save()) {
                $this->success('状态切换成功', 'Goods/index');
            } else {
                $this->error('状态切换失败', 'Goods/index');
            }
        } else {
            $this->error('商品不存在', 'Goods/index');
        }
    }

    public function edit($id)
    {
        $goods = GoodsModel::find($id);
        if (!$goods) {
            $this->error('商品不存在');
        }

        $this->assign('goods', $goods);
        return $this->fetch();
    }

    public function editPost()
    {
        if ($this->request->isPost()) {
            $data = input('post.');

            //验证数据
            $validate = new goodsValidate();
            $result = $validate->scene('edit')->check($data);
            if (!$result) {
                return json(['code' => 0, 'msg' => $validate->getError(), 'data' => null]);
            }


            $news = goodsModel::find($data['id']);
            if (!$news) {
                $this->error('商品不存在');
            }
            // 处理内容中的图片地址
            //switch的默认值
            $data['switch'] = 1;

            $news->name = $data['name'];
            $news->image = $data['image'];
            $news->status = $data['status'];
            $news->gid = $data['gid'];
            $news->rmb = $data['rmb'];
            $news->zy = $data['zy'];
            $news->switch = $data['switch'];
            $news->update_time = date('Y-m-d H:i:s');
            if(empty($data['images'])) {
                if ($news->save()) {
                    $this->success('编辑成功', url('goods/index'));
                } else {
                    $this->error('编辑失败');
                }
            }
            $data['images'] = implode(',',$data['images']);
            $news->images = $data['images'];
            if ($news->save()) {
                $this->success('编辑成功', url('goods/index'));
            } else {
                $this->error('编辑失败');
            }
        }
    }

    public function delete($id)
    {
        $goods = GoodsModel::find($id);
        if (!$goods) {
            $this->error('商品不存在');
        }

        if ($goods->delete()) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

    public function order()
    {
        parent::listOrders(new GoodsModel());
        $this->success('排序成功');
    }

    //打开配置页面
    public function setGoodsAttr()
    {
        $goods_id = input('goods_id');
        $this->assign('goods_id',$goods_id);
        return $this->fetch('add_goods_attr2');
    }

    //配置提交
    public function setGoodsAttrPost()
    {
        $attrs = input('post.attr');
        $goodsId = input('post.goods_id');
        if (count($attrs) < 1){
            $this->error('请至少配置一个属性！');
        }
        Db::name('goods_attr')->where('goods_id',$goodsId)->delete();
        $insert_data = [];
        foreach ($attrs as $attr) {
            $insert_data[] = [
                'goods_id' => $goodsId,
                'name' => $attr['name']
            ];
        }
        Db::name('goods_attr')->insertAll($insert_data);
        $this->success('保存成功');
    }

    //打开配置商品属性值页面
    public function setGoodsAttrValue()
    {

        $goods_id = input('goods_id');

        $this->assign('goods_id',$goods_id);

        return $this->fetch('add_goods_attr_value');
    }

    //提交表单
    public function setGoodsAttrValuePost()
    {
        $date = input('post.form');

        if (count($date) < 1){
            $this->error('请至少配置一个属性！');
        }
        $insert_data = [];
        foreach ($date as $attrs) {
            $insert_data[] = [
                'attr_id' => $attrs['attr'],
                'name' => $attrs['attr_value']
            ];
        }
        Db::name('goods_attr_value')->insertAll($insert_data);
        $this->success('保存成功');
    }

    //查询某个商品有哪些属性
    public function getGoodsAttr()
    {
        $goods_id = input('goods_id');
        //查询商品属性
        $attrs = Db::name('goods_attr')->where('goods_id',$goods_id)->select();
        return json(['code' => 1,'msg' => '商品属性','data' => $attrs]);

    }

    //查询某个商品有哪些属性
    public function getGoodsAttr2()
    {

        $goods_id = input('goods_id');
        //查询商品属性
        $attrs = Db::name('goods_attr')->where('goods_id',$goods_id)->select();
        return json(['code' => 1,'msg' => '商品属性','data' => $attrs]);
    }

    //打开配置页面
    public function setGoodsAttrs()
    {
        $goods_id = input('goods_id');
        $this->assign('goods_id',$goods_id);
        return $this->fetch('add_goods_attr3');
    }

    public function setGoodsAttrsPost()
    {
        $goods_id = input('post.goods_id');
        $form = input('post.form');
        GoodsModel::update([
            'attr' => json_encode($form,JSON_UNESCAPED_UNICODE)
        ],['id' => $goods_id] );
    }
}
